package com.entrogy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.Table;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.service.PermissionService;
import com.entrogy.service.SalarySlipService;
import com.entrogy.service.UserService;
import com.entrogy.utils.EasyExcelUtil;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName SalarySlipController
 * @Description 注意：此接口的权限控制全部由PC段设置，和shiro共用同一套权限系统
 * @Author luoxingjiang
 * @Date 2019/8/27 0027 下午 1:34
 * @Version 1.0
 **/
@RestController
@RequestMapping("/salary-slip")
@Api(description = "工资条操作相关接口")
public class SalarySlipController {

    private Logger logger = LoggerFactory.getLogger(SalarySlipController.class);

    @Autowired
    private SalarySlipService salarySlipService;

    @Autowired
    private UserService userService;

    @Autowired
    private EasyExcelUtil easyExcelUtil;

    @Autowired
    private PermissionService permissionService;

    @Value("${show.image.url}")
    private String showImage;

    @GetMapping(value = "/list")
    @ApiOperation(value = "查看工资条模板，暂时一个学校只能有一个工资模板id")
    public Msg listSalarySlipTemplate(@RequestParam(value = "userId", required = false) String userId){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        // 判断是否有查看工资条的权限
        String permissionCode = "salary_template:list";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有查看工资条模板的权限！");
        }
        Integer templateId = salarySlipService.getSalarySlipTemplateIdBySchoolCode(schoolCode);
        List<SalarySlipTemplateEntity> salarySlipTemplateList = new ArrayList<>();
        if (templateId == null){
            return Msg.success().add("salarySlipTemplateList", salarySlipTemplateList);
        }
        salarySlipTemplateList = salarySlipService.listSalarySlipTemplate(templateId, 1);
        return Msg.success().add("salarySlipTemplateList", salarySlipTemplateList);
    }

    @PutMapping(value = "/insert")
    @ApiOperation(value = "新增工资条模板，暂时一个学校只能有一个工资模板id")
    public Msg insertSalarySlipTemplate(@RequestBody SalarySlipTemplateEntity salarySlipTemplate){
        // 判断是否有空白工资条组成
        List<SalaryComposeEntity> salaryComposeList = salarySlipTemplate.getSalaryComposeList();
        for (SalaryComposeEntity salaryComposeEntity : salaryComposeList) {
            if (!StringUtils.isNoneBlank(salaryComposeEntity.getSalaryComposeName())){
                return Msg.fail(ErrorEnum.E_101, "对不起，添加失败，工资条组成不能为空！");
            }
        }
        // 判断是否有新增工资条的权限
        String userId = salarySlipTemplate.getCreateUserId();
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
            salarySlipTemplate.setCreateUserId(userId);
        }
        String permissionCode = "salary_template:add";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有查看工资条模板的权限！");
        }
        // 模板内必须要有工资组成
        if (salarySlipTemplate.getSalaryComposeList().size() == 0){
            return Msg.fail(ErrorEnum.E_502, "您尚未在模板内添加任何工资组成，请添加后再创建模板！");
        }
        boolean result = salarySlipService.insertSalarySlipTemplate(salarySlipTemplate);
        if (result){
            return Msg.success();
        }
        return Msg.fail(ErrorEnum.E_101, "创建模板失败！");
    }

    @PutMapping(value = "/update")
    @ApiOperation(value = "修改工资条模板")
    public Msg updateSalarySlipTemplate(@RequestBody SalarySlipTemplateEntity salarySlipTemplate){
        // 判断是否有权限
        String userId = salarySlipTemplate.getCreateUserId();
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
            salarySlipTemplate.setCreateUserId(userId);
        }
        String permissionCode = "salary_template:update";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有修改工资条模板的权限！");
        }
        boolean result = salarySlipService.updateSalarySlipTemplate(salarySlipTemplate);
        return Msg.success();
    }

    @GetMapping(value = "/export")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "isExportTemplate", value = "是否是导出模板，导出模板的话，工资数据默认为0，1表示导出模板，0表示导出工资数据", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "salaryYear", value = "要导出工资条的信息的年份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "salaryMonth", value = "要导出工资条的信息的月份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
    })
    @ApiOperation(value = "导出工资条模板&工资条信息")
    public Msg updateSalarySlipTemplate(HttpServletRequest request, HttpServletResponse response){
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        String userId = "";
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            userId = request.getParameter("userId");
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        // 判断是否有权限
        String permissionCode = "salary:export";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有导出工资条的权限！");
        }
        Integer templateId = salarySlipService.getSalarySlipTemplateIdBySchoolCode(schoolCode);
        Integer isExportTemplate = Integer.valueOf(request.getParameter("isExportTemplate"));
        Integer salaryYear = null;
        Integer salaryMonth = null;
        if (request.getParameter("salaryYear") != null){
            salaryYear = Integer.valueOf(request.getParameter("salaryYear"));
        }
        if (request.getParameter("salaryMonth") != null){
            salaryMonth = Integer.valueOf(request.getParameter("salaryMonth"));
        }
        if (isExportTemplate == 0 && salaryYear == null && salaryMonth == null){
            return Msg.fail(ErrorEnum.E_502, "请选择月份之后才能进行导出！");
        }
        // 查询出工资条模板的组成
        // 查询所有状态的组成
        SalarySlipTemplateEntity salarySlipTemplate = salarySlipService.listSalarySlipTemplate(templateId, null).get(0);
        // 查询出该次要发工资的所有员工
        List<JSONObject> userList = userService.listSchoolAllUser(schoolCode);
        // 初始化完成后
        ServletOutputStream out;
        try{
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName;
            if (isExportTemplate == 1){
                fileName = URLEncoder.encode("工资表模板","utf-8");
            }else {
                fileName = URLEncoder.encode(salaryYear + "年" + salaryMonth + "月工资表","utf-8");
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 查找该模板的工资构成
            List<SalaryComposeEntity> salaryComposeList = salarySlipTemplate.getSalaryComposeList();
            List<SalaryTeacherInfoEntity> teacherSalaryInfoList = new ArrayList<>();
            //如果是导出工资数据的话，那么需要查询工资数据，导出模板不需要查询
            if (isExportTemplate == 0){
                teacherSalaryInfoList = salarySlipService.listTeacherSalaryInfo(salaryYear, salaryMonth, null, schoolCode);
                if (teacherSalaryInfoList.size() == 0){
                    return Msg.fail(ErrorEnum.E_502, "您尚未导入"+ salaryYear + "年" + salaryMonth + "月" +"的任何工资数据，不能进行该月的工资数据导出！");
                }
            }
            logger.debug("需要导出的工资数据=>" + teacherSalaryInfoList.toString());
            // 写sheet1，表头数据动态传入
            // 查询该该工资条模板由哪些组成，用于设置动态表头并实现分数的填充
            List<List<String>> head = new ArrayList<>();
            List<String> headCoulumn1 = new ArrayList<>();
            headCoulumn1.add("工资条构成ID");
            headCoulumn1.add("工号");
            List<String> headCoulumn2 = new ArrayList<>();
            headCoulumn2.add("工资条构成ID");
            headCoulumn2.add("姓名");
            head.add(headCoulumn1);
            head.add(headCoulumn2);
            for (int i = 0; i < salaryComposeList.size(); i++) {
                SalaryComposeEntity salaryCompose = salaryComposeList.get(i);
                if (salaryCompose.getEnable() == 0){
                    continue;
                }
                List<String> headCoulumn = new ArrayList<>();
                headCoulumn.add(String.valueOf(salaryCompose.getId()));
                headCoulumn.add(salaryCompose.getSalaryComposeName());
                head.add(headCoulumn);
            }
            // 动态添加表头，适用一些表头动态变化的场景
            EasyExcel.write(out)
                    // 这里放入动态头
                    .head(head).sheet("sheet1")
                    // 当然这里数据也可以用 List<List<String>> 去传入
                    .doWrite(createDynamicModelList(teacherSalaryInfoList, salaryComposeList, userList, isExportTemplate));
            // 关闭流
            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return Msg.success();
    }

    @PostMapping("/import-salary")
    @ApiOperation(value = "导入工资条")
    public Msg importSalary(@RequestParam("excelFile") MultipartFile excelFile,  @RequestParam("salaryYear") Integer salaryYear, @RequestParam("salaryMonth") Integer salaryMonth, @RequestParam(value = "userId", required = false) String userId) throws IOException {
        // 判断是否有权限
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        String permissionCode = "salary:import";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有导入工资条的权限！");
        }
        Integer templateId = salarySlipService.getSalarySlipTemplateIdBySchoolCode(schoolCode);
        easyExcelUtil.resolveExcelWithSalary(excelFile.getInputStream(), salaryYear, salaryMonth, templateId, userId, schoolCode, salarySlipService);
        return Msg.success();
    }

    @GetMapping("/get-teacher-salary")
    @ApiOperation(value = "查看教师工资信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "当前小程序用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "salaryInfoId", value = "工资条id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "viewMyself", value = "是否是查看自己的工资信息，0表示不是，1表示是", dataType = "Integer", paramType = "query"),
    })
    public Msg getTeacherSalary(@RequestParam(value = "userId", required = false) String userId, @RequestParam(value = "salaryInfoId") Integer salaryInfoId,  @RequestParam(value = "viewMyself") Integer viewMyself) {
        // 不是查看自己的工资的话，需要判断权限
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        if(viewMyself == 0){
            // 判断是否有权限
            String permissionCode = "salary:list";
            boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
            if (!hasPermission){
                logger.info("工资条权限不足");
                return Msg.fail(ErrorEnum.E_502,"对不起，您没有查看其他人工资的权限！");
            }
        }
        if (salaryInfoId.equals(-1)){
            return Msg.fail(ErrorEnum.E_502, "没有此工资条信息！");
        }
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }
        Integer templateId = salarySlipService.getSalarySlipTemplateIdBySchoolCode(schoolCode);
        // 如果是查看自己的信息的话将该条工资条状态设置为已读
        if (viewMyself.equals(1)){
            boolean updateSalaryInfo = salarySlipService.updateSalaryInfoStatus(null, 2, null, null, salaryInfoId);
        }
        List<SalaryTeacherInfoEntity> teacherSalaryInfoList = salarySlipService.listTeacherSalaryInfo(null, null, salaryInfoId, schoolCode);
        return Msg.success().add("teacherSalaryInfoList", teacherSalaryInfoList);
    }

    @PutMapping("/update-teacher-salary")
    @ApiOperation(value = "更新教师工资信息")
    public Msg updateTeacherSalary(@RequestBody UpdateTeacherSalaryEntity teacherSalaryDetail) {
        // 判断是否有权限
        String userId = teacherSalaryDetail.getUserId();
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String)SecurityUtils.getSubject().getSession().getAttribute("userId");
            teacherSalaryDetail.setUserId(userId);
        }
        String permissionCode = "salary:update";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有更新工资信息的权限！");
        }
        boolean result = salarySlipService.updateSalaryDetail(teacherSalaryDetail);
        if (result){
            return Msg.success();
        }
        return Msg.fail(ErrorEnum.E_502, "对不起，教师工资信息更新失败！");
    }

    @GetMapping("/salary-slip-month-overview")
    @ApiOperation(value = "办公室职员查看工资条发送、阅读、确认状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "条数", dataType = "Integer", paramType = "query"),
    })
    public Msg ListSalarySlipMonthOverview(@RequestParam(value = "userId", required = false) String userId,@RequestParam(value = "currentPage", required = false) Integer currentPage,
                                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        // 判断是否有权限
        String permissionCode = "salary:list";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有查看工资条的权限！");
        }
        Integer totalCount = salarySlipService.countMonthSalary(schoolCode);
        PageHelper.startPage(currentPage == null ? 1 : currentPage, pageSize == null ? 10 : pageSize);
        List<MonthSalaryStatusEntity> monthSalaryStatusList = salarySlipService.listMonthSalaryStatus(schoolCode);
        return Msg.success().add("monthSalaryStatusList", monthSalaryStatusList).add("totalCount", totalCount);
    }

    @GetMapping("/list-teacher-salary-slip-status")
    @ApiOperation(value = "办公室职员查看所有教师工资条状态信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "salaryYear", value = "查看的工资条的信息的年份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "salaryMonth", value = "查看的工资条的信息的月份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "条数", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
    })
    public Msg ListTeacherSalarySlip(@RequestParam(value = "salaryYear", required = false) Integer salaryYear,
                                     @RequestParam(value = "salaryMonth", required = false) Integer salaryMonth,
                                     @RequestParam(value = "currentPage", required = false) Integer currentPage,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                     @RequestParam(value = "userId", required = false) String userId) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        // 判断是否有权限
        String permissionCode = "salary:list";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有查看工资条的权限！");
        }
        if (currentPage == null){
            currentPage = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        Integer totalCount = salarySlipService.countTeacherSalarySlip(schoolCode, salaryYear, salaryMonth, null);
        PageHelper.startPage(currentPage, pageSize);
        List<SalaryTeacherInfoEntity> teacherSalaryInfoList = salarySlipService.listTeacherSalarySlipInfo(schoolCode, salaryYear, salaryMonth, null);
        return Msg.success().add("teacherSalaryInfoList", teacherSalaryInfoList).add("showImage", showImage).add("totalCount", totalCount);
    }

    @GetMapping("/get-teacher-salary-slip-status")
    @ApiOperation(value = "教师查看自己的所有工资条状态信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "salaryYear", value = "查看的工资条的信息的年份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "salaryMonth", value = "查看的工资条的信息的月份", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "currentPage", value = "当前页", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "条数", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
    })
    public Msg getTeacherSalarySlip(@RequestParam(value = "salaryYear", required = false) Integer salaryYear,
                                    @RequestParam(value = "salaryMonth", required = false) Integer salaryMonth,
                                    @RequestParam(value = "currentPage", required = false) Integer currentPage,
                                    @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                    @RequestParam(value = "userId", required = false) String userId
                                    ) {
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        // 如果没有登录，那么就是小程序端的请求
        if (schoolCode == null){
            schoolCode = userService.getSchoolCodeByUserId(userId);
        }else {
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        if (currentPage == null){
            currentPage = 1;
        }
        if (pageSize == null){
            pageSize = 10;
        }
        Integer totalCount = salarySlipService.countTeacherSalarySlip(schoolCode, salaryYear, salaryMonth, userId);
        PageHelper.startPage(currentPage, pageSize);
        List<SalaryTeacherInfoEntity> teacherSalaryInfoList = salarySlipService.listTeacherSalarySlipInfo(schoolCode, salaryYear, salaryMonth, userId);
        return Msg.success().add("teacherSalaryInfoList", teacherSalaryInfoList).add("showImage", showImage).add("totalCount", totalCount);
    }

    @PostMapping("/confirm-salary-slip")
    @ApiOperation(value = "教师确认工资条")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "salaryInfoId", value = "工资条id", dataType = "Integer", paramType = "query"),
    })
    public Msg confirmTeacherSalarySlip(@RequestParam(value = "salaryInfoId") Integer salaryInfoId,
                                        @RequestParam(value = "userId") String userId) {
        boolean result = salarySlipService.updateSalaryInfoStatus(null, null, 2, null, salaryInfoId );
        if (result){
            return Msg.success();
        }
        return Msg.fail(ErrorEnum.E_502, "对不起，确认失败！");
    }

    @PostMapping("/send-salary-slip")
    @ApiOperation(value = "办公室职员发送工资条")
    public Msg sendSalarySlip(@RequestParam("salaryInfoIdList") List<Integer> salaryInfoIdList, @RequestParam(value = "userId", required = false) String userId) {
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        return batchSendSalary(salaryInfoIdList, userId);
    }

    @PostMapping("/send-salary-slip-all")
    @ApiOperation(value = "办公室职员发送工资条(直接发送某月的全部工资条信息)")
    public Msg sendSalarySlip(@RequestParam(value = "salaryYear") Integer salaryYear, @RequestParam(value = "salaryMonth") Integer salaryMonth, @RequestParam(value = "userId", required = false) String userId) {
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
        List<Integer> salaryInfoIdList = salarySlipService.listMonthSalaryInfoId(salaryYear, salaryMonth, schoolCode);
        return batchSendSalary(salaryInfoIdList, userId);
    }

    @PostMapping("/recall-salary-slip")
    @ApiOperation(value = "办公室职员撤回工资条")
    public Msg recallSalarySlip(@RequestParam("salaryInfoIdList") List<Integer> salaryInfoIdList, @RequestParam(value = "userId", required = false) String userId) {
        // 判断是否有权限
        String permissionCode = "salary:send";
        if (!StringUtils.isNoneBlank(userId)){
            userId = (String) SecurityUtils.getSubject().getSession().getAttribute("userId");
        }
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有撤回工资条的权限！");
        }
        // 查询出这些工资条所属教师的电话号码用于通知教师该月工资条被撤回
        List<String> phoneList = salarySlipService.listPhoneBySalaryInfoId(salaryInfoIdList);
        // 撤回工资条修改状态即可
        for (Integer salaryInfoId : salaryInfoIdList) {
            boolean result = salarySlipService.updateSalaryInfoStatus(null, null, null, 2, salaryInfoId );
            if (!result){
                return Msg.fail(ErrorEnum.E_502, "对不起，撤回失败！");
            }
        }
        String[] paramsMobile = new String[2];
        paramsMobile[0] = "本月工资条信息有误，已被管理员撤回，且正在为您重新核算，请耐心等待！";
        // 适配该通知的短信模板
        paramsMobile[1] = "";
        for (String phone : phoneList) {
            SendUtils.sendByShortMessage(phone, paramsMobile, "200643");
        }
        return Msg.success();
    }

    //根据动态列生成动态的数据，
    private List<List<Object>> createDynamicModelList(List<SalaryTeacherInfoEntity> salaryTeacherInfoList, List<SalaryComposeEntity> salaryComposeList, List<JSONObject> userList, Integer isExportTemplate){
        List<List<Object>> rows = new ArrayList<>();
        if (isExportTemplate == 1){
            //如果是导出模板的话，那么每一行数据就是教师id+教师姓名，其余工资数据均为0
            for (int i = 0; i < userList.size(); i++) {
                JSONObject teacherInfo = userList.get(i);
                List<Object> row = new ArrayList<>();
                row.add(teacherInfo.getString("id"));
                row.add(teacherInfo.getString("name"));
                rows.add(row);
            }
        }else {
            for (int i = 0; i < salaryTeacherInfoList.size(); i++) {
                SalaryTeacherInfoEntity salaryTeacherInfo = salaryTeacherInfoList.get(i);
                List<Object> row = new ArrayList<>();
                row.add(salaryTeacherInfo.getTeacherId());
                row.add(salaryTeacherInfo.getTeacherName());
                List<SalaryTeacherDetailEntity> salaryTeacherDetailList = salaryTeacherInfo.getSalaryTeacherDetailList();
                for (int k = 0; k < salaryComposeList.size(); k++) {
                    SalaryComposeEntity salaryCompose = salaryComposeList.get(k);
                    for (int j = 0; j < salaryTeacherDetailList.size(); j++) {
                        SalaryTeacherDetailEntity salaryTeacherDetail = salaryTeacherDetailList.get(j);
                        //写每一行教师的工资数据时，需要比对工资组成id是否和当前列的工资组成id一致
                        if (salaryCompose.getId().equals(salaryTeacherDetail.getSalaryComposeId())){
                            row.add(salaryTeacherDetail.getValue() == null ? 0 : salaryTeacherDetail.getValue());
                        }
                    }
                }
                rows.add(row);
            }
        }
        return rows;
    }

    @GetMapping("/is-personnel-manager")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "String", paramType = "query"),
    })
    @ApiOperation(value = "判断是否有查看他人工资条及修改工资信息的权限")
    public Msg isPersonnelManager(String userId) {
        // 判断是否有权限，暂时只通过判断他是否能看所有人的工资条信息来判断他是否拥有工资条管理这个菜单
        String permissionCode = "salary:list";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("您不是人事部职员，无法使用工资条管理！userId=>" + userId);
            return Msg.fail(ErrorEnum.E_502,"您不是人事部职员，无法使用工资条管理！");
        }
        return Msg.success().add("isPersonnelManager", true);
    }


    private Msg batchSendSalary(List<Integer> salaryInfoIdList, String userId){
        // 判断是否有权限
        String permissionCode = "salary:send";
        boolean hasPermission = permissionService.hasAuthorization(userId, permissionCode);
        if (!hasPermission){
            logger.info("工资条权限不足");
            return Msg.fail(ErrorEnum.E_502,"对不起，您没有发送工资条的权限！");
        }
        // 首先更改发送状态，发送状态更改的同时，需要将确认状态、已读状态、撤回状态重置为1，因为可能发送的是经过修改的撤回的工资条信息
        for (Integer salaryInfoId : salaryInfoIdList) {
            boolean result = salarySlipService.updateSalaryInfoStatus(2, 1, 1, 1, salaryInfoId );
            if (!result){
                return Msg.fail(ErrorEnum.E_502, "对不起，发送失败！");
            }
        }
        // 查询出这些工资条所属教师的电话号码用于通知教师该月工资条已发送，不发送工资信息，需要到小程序查看
        List<String> phoneList = salarySlipService.listPhoneBySalaryInfoId(salaryInfoIdList);
        String[] paramsMobile = new String[2];
        paramsMobile[0] = "本月工资条信息已发送，请登录小程序端查看详情信息！";
        //适配该通知的短信模板
        paramsMobile[1] = "";
        for (String phone : phoneList) {
            SendUtils.sendByShortMessage(phone, paramsMobile, "200643");
        }
        return Msg.success();
    }



}
